<?php

namespace App\Jobs\RabbitMQ;

use App\Consts\GlobalConst;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class MsgConsumer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $data;

    private $uid;

    /**
     * Create a new job instance.
     *
     * @param $data
     */
    public function __construct($data)
    {
        $this->data = $data;
        $this->uid = uniqid();
        Log::info('[RMQ][MSG][ENTER] - uid : ' . $this->uid);
    }

    /**
     * Execute the job.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('[RMQ][MSG][HANDLE] - uid : ' . $this->uid . ' - data : ' . json_encode($this->data));
        try {
            // 消费消息队列
            service()->RabbitMQService->consumer($this->data['envelope'], $this->data['queue']);
            return true;
        } catch (\Exception $e) {
            $flag = GlobalConst::ERROR_FILE_FLAG;
            $info = '[RMQ][MSG][CATCH] - ' . json_encode([
                'msg' => $e->getMessage(),
                'code' => $e->getCode(),
                'status' => 'failed',
                'result' => [
                    'file' => $flag . ' : ' . $e->getFile() . ' - ' . $e->getLine(),
                    'data' => $this->data,
                    'uid' => $this->uid,
                ]
            ]);
            Log::error($info);
            echo $info;
            return false;
        }
    }

}
